{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from PIL import Image, ImageDraw\n",
    "import os\n",
    "import cv2\n",
    "import time\n",
    "import random\n",
    "import tensorflow as tf\n",
    "\n",
    "from detector import Detector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "MODEL_PATH = 'model.pb'\n",
    "detector = Detector(MODEL_PATH, gpu_memory_fraction=0.5, visible_device_list='0')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Utils for box drawing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def draw_boxes_on_image(image, boxes, labels, scores):\n",
    "\n",
    "    image_copy = image.copy()\n",
    "    draw = ImageDraw.Draw(image_copy, 'RGBA')\n",
    "    width, height = image.size\n",
    "    scaler = np.array([height, width, height, width], dtype='float32')\n",
    "    boxes = boxes.copy() * scaler\n",
    "\n",
    "    for b, l, s in zip(boxes, labels, scores):\n",
    "        ymin, xmin, ymax, xmax = b\n",
    "        fill = (255, 0, 0, 45)\n",
    "        outline = 'red'\n",
    "        draw.rectangle(\n",
    "            [(xmin, ymin), (xmax, ymax)],\n",
    "            fill=fill, outline=outline\n",
    "        )\n",
    "        draw.text((xmin, ymin), text='{0} {1:.3f}'.format(decoder[l], s))\n",
    "    return image_copy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load label decoder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../data/coco_labels.txt', 'r') as f:\n",
    "    labels = {line.strip(): i for i, line in enumerate(f.readlines()) if line.strip()}\n",
    "    \n",
    "decoder = {i: n for n, i in labels.items()}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Get an image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "folder = '/home/dan/datasets/COCO/images/val2017/'\n",
    "names = os.listdir(folder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = names[100]\n",
    "# n = random.choice(names)\n",
    "\n",
    "image = cv2.imread(os.path.join(folder, n))\n",
    "image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
    "image = Image.fromarray(image)\n",
    "image = image.resize((896, 640))\n",
    "image"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Show detections"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "image_array = np.array(image)\n",
    "boxes, labels, scores = detector(image_array, score_threshold=0.5)\n",
    "draw_boxes_on_image(image, boxes, labels, scores)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Measure speed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "times = []\n",
    "for _ in range(110):\n",
    "    start = time.perf_counter()\n",
    "    boxes, labels, scores = detector(image_array, score_threshold=0.5)\n",
    "    times.append(time.perf_counter() - start)\n",
    "    \n",
    "times = np.array(times)\n",
    "times = times[10:]\n",
    "print(times.mean(), times.std())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
